package com.sales.service.data.transaction;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.sales.service.constants.ServiceConstants;
import com.sales.service.data.transaction.containers.TaskContainer;
import com.sales.service.data.transaction.notifier.ResponseListeners;
import com.sales.service.data.transaction.notifier.UINotifier;
import com.sales.service.http.ServiceRequest;
import com.sales.service.queue.ServiceQueueManager;
import com.sales.service.utils.Utility;

/**
 * This class is used to create the request url for the task informations.
 * the request is made and sent to the queue.
 * with the notifier concept to throw the output of the request from the thread
 * to the UI.
 *  
 * @author Sega
 *
 */
public class TaskTransaction extends AbstractTransaction implements	ResponseListeners {

	/**
	 * Strings for debugging process by log.i method
	 */
	private static final String TagProject = "SalesService";
	private static final String TagPage = "TaskTransc ::";

	/**
	 * Declaration of the notifier.
	 */
	private final UINotifier notify;

	/**
	 * constructor - is used to initiate the request for the thread
	 * this is done by the abstract method.
	 * 
	 * @param notify - the class to notify is obtained
	 */
	public TaskTransaction(UINotifier notify) {
		this.notify = notify;
		initiateTransaction();
	}

	/* (non-Javadoc)
	 * @see com.sales.service.data.transaction.AbstractTransaction#initiateTransaction()
	 * 
	 * this is the abstract method overridden to initiate the thread request and 
	 * to queue.
	 * 
	 */
	@Override
	protected void initiateTransaction() {
		String taskUrl = getBaseUrl() + ServiceConstants.SF_Q_GET_LEAD;
		ServiceRequest taskRequest = new ServiceRequest();
		taskRequest.setRequesturl(taskUrl);
		taskRequest.setResponseListener(this);
		ServiceQueueManager.getInstance().queuePut(taskRequest);
		Log.i(TagProject,TagPage + "taskUrl: " + taskRequest.getRequesturl());
	}

	/* (non-Javadoc)
	 * @see com.sales.service.data.transaction.notifier.ResponseListeners#executeResponse(java.io.InputStream)
	 * 
	 * This is the overridden method of RsponseListener class
	 * to get the content of the entity.
	 * 
	 */
	@Override
	public void executeResponse(InputStream response) throws JSONException,	IOException {
		Log.i(TagProject, TagPage + "TaskResponse obtained.");
		String res = Utility.WiteFiletosd(response, "Task.json");
		deserializeJson(res);
	}

	/* (non-Javadoc)
	 * @see com.sales.service.data.transaction.AbstractTransaction#deserializeJson(java.lang.String)
	 * 
	 * This method is used to store the datas available in the obtained entity
	 * in a array list of the respective container object.
	 * then it handles them as the message and updates the UI as onsuccess method.
	 * 
	 */
	@Override
	protected void deserializeJson(String response) throws JSONException {

		JSONObject jsonObject = new JSONObject(response);
		JSONArray recondresonse = jsonObject.getJSONArray("records");

		String totalsize = jsonObject.getString("totalSize");
		// String done =jsonObject.getString("done");
		Log.i(TagProject, TagPage + "Total Size: " + totalsize);

		ArrayList<Object> arrayLeadResult = new ArrayList<Object>();
		TaskContainer container[] = new TaskContainer[recondresonse.length()];
		for (int index = 0; index < recondresonse.length(); index++) {

			JSONObject recordobject = recondresonse.getJSONObject(index);

			container[index] = new TaskContainer();
			container[index].setSubject(recordobject.getString("Company"));
			container[index].setDueDate(recordobject.getString("FirstName"));
			// container[index].setLastName(recordobject.getString("LastName"));
			// container[index].setStreet(recordobject.getString("Street"));
			// container[index].setCity(recordobject.getString("City"));
			// container[index].setState(recordobject.getString("State"));
			// container[index].setPostalcode(recordobject.getString("PostalCode"));

			arrayLeadResult.add(container[index]);

		}

		Message msg = new Message();
		msg.obj = arrayLeadResult;
		handler.sendMessage(msg);
	}

	/**
	 * This is the handler used to send the result of the thread to the 
	 * UI as a message.
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			ArrayList<Object> arrayTaskResult = (ArrayList<Object>) msg.obj;

			if (arrayTaskResult.size() != 0) {
				Log.i(TagProject, TagPage + "All records Obtained and Notified.");
				notify.onSuccess(arrayTaskResult);
			} else {
				Log.i(TagProject, TagPage + "NO records.");
				notify.onError();
			}
			
		}
	};

}